import { ref } from "vue";

export default function useMap(mapContainerId = "mapContainer") {
  const map = ref<any>(null);
  const markers = ref<any>([]);

  // 初始化地图
  function initMap(
    latitude: number | string = "25.83368",
    longitude: number | string = "114.93417"
  ) {
    if (!(window as any).T.Map) {
      console.error("T.Map library is not loaded properly.");
      return;
    }
    map.value = new (window as any).T.Map(mapContainerId);
    const lnglat = new (window as any).T.LngLat(longitude, latitude);
    map.value.centerAndZoom(lnglat, 12);
    const control = new (window as any).T.Control.Zoom();
    const scale = new (window as any).T.Control.Scale();
    map.value.on("click", handlClickMap);
    map.value.addControl(control);
    map.value.addControl(scale);
  }

  // 添加标记
  function addMarker(position: any) {
    if (!map.value) return;
    const marker = new (window as any).T.Map.MultiMarker({
      map: map.value
    });
    marker.setMap(map.value);
    marker.add({
      position
    });
    markers.value.push(marker);
  }

  // 移除所有标记
  function removeAllMarkers() {
    markers.value.forEach((marker: any) => marker.setMap(null));
    markers.value = [];
  }

  const handlClickMap = (e: any) => {
    removeAllMarkers();
    addMarker(e.latLng);
  };

  return {
    map,
    markers,
    initMap,
    addMarker,
    removeAllMarkers
  };
}
